package main

import (
	"fmt"
	"os"
	"path/filepath"

	"github.com/xuri/excelize/v2"
)

// Convert index to Excel-style column letter (e.g., 0 -> "A", 1 -> "B", etc.)
func toAlphaString(index int) string {
	result := ""
	for index >= 0 {
		result = string(rune('A'+(index%26))) + result
		index = index/26 - 1
	}
	return result
}

func WriteExcelData(filename string, data []map[string]string, config *Config) error {
	f := excelize.NewFile()
	defer f.Close()

	// 设置表头
	for colIdx, header := range config.Headers {
		column := toAlphaString(colIdx) // 使用自定义函数转换为列字母
		cell := fmt.Sprintf("%s%d", column, 1)
		if err := f.SetCellValue("Sheet1", cell, header.Name); err != nil {
			return err
		}
	}

	// 写入数据，保证每个学生数据写在单独的一行
	for rowIdx, studentData := range data {
		rowNum := rowIdx + 2 // 从第二行开始写入数据
		for colIdx, header := range config.Headers {
			column := toAlphaString(colIdx) // 使用自定义函数转换为列字母
			cell := fmt.Sprintf("%s%d", column, rowNum)
			if err := f.SetCellValue("Sheet1", cell, studentData[header.Name]); err != nil {
				return err
			}
		}
	}

	// 保存文件
	outputPath := filepath.Join(config.OutputDirectory, filename)
	if err := os.MkdirAll(config.OutputDirectory, os.ModePerm); err != nil {
		return err
	}
	return f.SaveAs(outputPath)
}
